#include "key.h"
#include "ui_key.h"
#include <QDebug>
#include <QMessageBox>

key::key(QVector<keyinfo> &ki, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::key),
    kinfo(ki)
{
    ui->setupUi(this);
    qDebug() << "start key";
    keyInit();
//    if (kinfo.size() > 0) {
//        ui->name->setText(kinfo.at(0).name);
//        ui->publisher->setText(kinfo.at(0).publisher);
//        ui->type->setValue(kinfo.at(0).type);
//        ui->key_2->setText(QByteArray::fromBase64(kinfo.at(0).key));
//    }

    ui->pull->setEnabled(false);
    ui->push->setEnabled(false);
    this->setWindowTitle("key manager");
}

key::~key()
{
    qDebug() << "end key";
    delete ui;
}

void key::keyInit()
{
    ui->selectCB->clear();
    for(auto i : kinfo) {
        ui->selectCB->addItem(i.name);
    }
}

void key::on_selectCB_currentIndexChanged(int index)
{
    qDebug() << "index = " << index;
    if (index >= 0){
        ui->name->setText(kinfo.at(index).name);
        ui->publisher->setText(kinfo.at(index).publisher);
        ui->type->setValue(kinfo.at(index).type);
        ui->key_2->setText(QByteArray::fromBase64(kinfo.at(index).key));
    }

}

void key::on_add_clicked()
{
    if (ui->name->text().isEmpty()) {
        QMessageBox::warning(this, "error", QString("name can not be empty"));
        return;
    }
    for(auto i : kinfo) {
        if (i.name == ui->name->text()) {
            QMessageBox::warning(this, "error", QString("%1 is exist!").arg(i.name));
            return;
        }
    }
    if (ui->key_2->text().size()<32 && !ui->key_2->text().isEmpty()) {
        QMessageBox::critical(this, "error", "key must have 32 bytes character");
        return;
    }
    kinfo.append(keyinfo(ui->name->text(),ui->publisher->text(),ui->type->value(),ui->key_2->text().left(32).toLatin1()));
    keyInit();
    QMessageBox::information(this, "", "add key successfully");
    emit keyChange();
}

void key::on_delete_2_clicked()
{
    if (kinfo.size() <= 0) return;
    if (QMessageBox::question(this, "confirm", QString("are you sure delete key %1").arg(kinfo.at( ui->selectCB->currentIndex()).name)) != QMessageBox::Yes) {
        return;
    }
    kinfo.remove(ui->selectCB->currentIndex());
    keyInit();
    QMessageBox::information(this, "", "delete successfully");
    emit keyChange();
}
